import {
  Card,
  Empty,
  Input,
  List,
  message,
  Row,
  Space,
  Spin,
  Tooltip,
} from 'antd';
import { VersionManageAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import { getVersionDataSercvice } from '../services';
import React, { useContext, useEffect, useState } from 'react';
import { getKeyRouter } from '@/utils';
import InfiniteScroll from 'react-infinite-scroller';
import { SyncOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';
import { VersionUpdateContext } from '../common/UpdateContext';
import { history } from 'umi';
import cls from 'classnames';
import MyIcon from '@/components/MyIcon';
export const UpdateViewRight = React.forwardRef(
  ({}: VersionManageAPI.IUpdateViewRight, ref) => {
    const {
      curRes,
      dispatch,
      prefixCls,
      locationProps,
      reloadVersionInfo,
      leftVersionType,
      getVersionDetailData,
    } = useContext(VersionUpdateContext);
    const [isOnReload, setIsOnReload] = useState<boolean>(false);

    /**ref 逻辑处理 */
    // useImperativeHandle(ref, () => ({
    //   getVersionType: () => {
    //     defaultGetVersionData();
    //   },
    // }));

    /**
     * 保存的分页参数
     */
    const [scrollObj, setScrollObj] = useState<any>({
      total: 0,
      count: 0,
      loading: false,
      hasMore: true,
      // limit: 10,
    });

    /**
     *  保存 搜索框的数据
     */
    const [searchValue, setSearchValue] = useState<string>();

    /**
     * 保存查询的数据
     */
    const [myCompileData, setMyCompileData] = useState<Record<string, any>[]>(
      [],
    );

    /**
     * 获取我的编撰回调
     * @param res
     */
    const getVersionDataCallBack = (res: any) => {
      if (res && res?.msgFlag) {
        setMyCompileData(res?.rows);
        setScrollObj({
          ...scrollObj,
          loading: false,
          total: res.total,
        });
      } else {
        message.error(res?.msg);
      }
      setIsOnReload(false);
    };

    /**
     * 引入获取我的编撰接口
     */
    const { getVersionDataRun, getVersionDataLoading } = getVersionDataSercvice(
      getVersionDataCallBack,
    );

    /**初始化请求 */
    useEffect(() => {
      // defaultGetVersionData();
      if (String(leftVersionType)) {
        let payload = {
          ...scrollObj,
          page: 1,
          rows: 10,
          versionType: leftVersionType,
          upgradeNote: searchValue,
          isPublics: '1,2',
        };
        getVersionDataRun(payload);
      }
    }, [leftVersionType]);

    /**
     * 初始化获取数据
     */
    // const defaultGetVersionData = () => {
    //   let { count, limit } = scrollObj;
    //   count++;
    //   setScrollObj({
    //     ...scrollObj,
    //     count: count,
    //     loading: true,
    //   });
    //   let payload = {
    //     page: 1,
    //     rows: count * 10 + limit,
    //     versionType: leftVersionType,
    //     upgradeNote: searchValue,
    //     isPublics: '1,2',
    //   };
    //   getVersionDataRun(payload);
    // };

    /**
     * 处理超过多少字的tooltip
     */
    const handleTooltip = (str: string) => {
      let newStr: string = str;
      if (str && str?.length > 50) {
        newStr = str.substr(0, 50) + '...';
      }
      return newStr;
    };

    /**
     * 处理滚动加载
     */
    const scrollLoadHand = () => {
      let { count, total } = scrollObj;
      count++;
      if (myCompileData?.length >= total) {
        message.warning('没有更多数据了哦');
        setScrollObj({
          ...scrollObj,
          hasMore: false,
          loading: false,
        });
        return;
      }
      setScrollObj({
        ...scrollObj,
        loading: true,
        hasMore: true,
        count,
      });
      let payload = {
        ...scrollObj,
        page: 1,
        rows: count * 10,
        versionType: leftVersionType,
        upgradeNote: searchValue,
        isPublics: '1,2',
      };
      getVersionDataRun(payload);
      // defaultGetVersionData();
    };

    /**
     * 刷新
     */
    const reloadRight = () => {
      setScrollObj({
        ...scrollObj,
        count: 0,
      });
      setSearchValue('');
      setIsOnReload(true);
    };

    useEffect(() => {
      if (scrollObj?.count == 0 && isOnReload) {
        let payload = {
          ...scrollObj,
          page: 1,
          rows: 10,
          versionType: leftVersionType,
          upgradeNote: searchValue,
          isPublics: '1,2',
        };
        getVersionDataRun(payload);
        // defaultGetVersionData();
      }
    }, [leftVersionType, scrollObj?.count, isOnReload]);

    /**
     * 跳转详情页面
     * @param resObj
     */
    const gotoVersionDetail = (resObj: any) => {
      history.push({
        pathname: `/versionController/getVersionByID/{id}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: resObj?.id,
        },
      });
    };

    return (
      <Card
        title={'相关版本'}
        className={cls(pageStyles['page-view'], prefixCls + 'CardRightSearch')}
        bodyStyle={{
          height: '95%',
          padding: '5px 0px',
          overflow: 'hidden',
        }}
        extra={
          <Space>
            <div className={prefixCls + 'CardAutoComplete-autoInput'}>
              <Input
                placeholder="请按升级内容搜索"
                suffix={
                  <>
                    <SearchOutlined
                      onClick={() => {
                        let { count } = scrollObj;
                        let payload: any = {
                          ...scrollObj,
                          page: 1,
                          rows: 10,
                          versionType: leftVersionType,
                          upgradeNote: searchValue,
                          isPublics: '1,2',
                        };
                        getVersionDataRun(payload);
                      }}
                    />
                    &nbsp;
                    <SyncOutlined onClick={reloadRight} />
                  </>
                }
                value={searchValue}
                onChange={(e) => {
                  setSearchValue(e?.target?.value);
                }}
                onPressEnter={() => {
                  let { count } = scrollObj;
                  let payload: any = {
                    ...scrollObj,
                    page: 1,
                    rows: 10,
                    versionType: leftVersionType,
                    upgradeNote: searchValue,
                    isPublics: '1,2',
                  };
                  getVersionDataRun(payload);
                }}
              />
            </div>
            {/* <Button
              icon={<SyncOutlined />}
              type="primary"
              size="small"
              onClick={reloadRight}
            /> */}
          </Space>
        }
      >
        <Spin spinning={getVersionDataLoading}>
          <div className={pageStyles['InfiniteScrollView']}>
            <InfiniteScroll
              loadMore={scrollLoadHand}
              initialLoad={false}
              pageStart={1}
              useWindow={false}
              hasMore={!scrollObj?.loading && scrollObj?.hasMore}
            >
              {myCompileData && myCompileData?.length > 0 ? (
                <div
                  className={cls(
                    prefixCls + 'rightCompileStyle',
                    'compile-avatar',
                  )}
                >
                  <List
                    itemLayout="horizontal"
                    dataSource={myCompileData}
                    renderItem={(item) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={
                            <div>
                              <MyIcon
                                type="icon-version"
                                style={{ fontSize: '40px' }}
                              />
                            </div>
                          }
                          title={
                            <Tooltip
                              placement="topLeft"
                              title={handleTooltip(item.announceTitle)}
                            >
                              <a
                                onClick={() => {
                                  gotoVersionDetail(item);
                                }}
                                style={{
                                  maxWidth: '95%',
                                  display: 'block',
                                  float: 'none',
                                }}
                                className={pageStyles['over-flow-hidden']}
                              >
                                {item?.versionType == '0'
                                  ? '安卓端'
                                  : item?.versionType == '1'
                                  ? '苹果端'
                                  : item?.versionType == '2'
                                  ? '电脑端'
                                  : null}
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                {item?.publicNum?.toFixed(1)}
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                {item?.isPublic == '0'
                                  ? '未发布'
                                  : item?.isPublic == '1'
                                  ? '发布上线'
                                  : item?.isPublic == '2'
                                  ? '历史版本'
                                  : null}
                              </a>
                            </Tooltip>
                          }
                          description={
                            <Tooltip
                              placement="topLeft"
                              title={handleTooltip(
                                item?.upgradeNote?.contentText,
                              )}
                            >
                              <div
                                onClick={() => {
                                  gotoVersionDetail(item);
                                }}
                              >
                                <Row>
                                  <div
                                    style={{ maxWidth: '95%' }}
                                    dangerouslySetInnerHTML={{
                                      __html: item?.upgradeNote?.contentText,
                                    }}
                                    className={pageStyles['over-flow-hidden']}
                                  />
                                </Row>
                                <Row>
                                  <div
                                    style={{
                                      textAlign: 'right',
                                      width: '100%',
                                      marginTop: '4px',
                                      fontSize: '12px',
                                    }}
                                  >
                                    {moment(item.createTime).format(
                                      'YYYY-MM-DD',
                                    )}
                                  </div>
                                </Row>
                              </div>
                            </Tooltip>
                          }
                        />
                      </List.Item>
                    )}
                  />
                  {scrollObj?.loading && scrollObj?.hasMore && (
                    <div>
                      <Spin />
                    </div>
                  )}
                </div>
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </InfiniteScroll>
          </div>
        </Spin>
      </Card>
    );
  },
);
